﻿using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 通过名字反射出类
/// 并实例化对象
/// 并加到缓存
/// </summary>
public class DataTablesManager {
    private static Dictionary<string, CSVReader> csvCache = new Dictionary<string, CSVReader>();

    public static Dictionary<string, CSVReader> CsvCache {
        get { return DataTablesManager.csvCache; }
    }
    public const string Path = "DataTables/";

    public static void Init() {
        for (int i = 0; i < DataTableAllName.DataTableNames.Length; i++) {
            var name = DataTableAllName.DataTableNames[i];
            GetCsvData(name);
        }
    }

    public static CSVReader GetCsvData(string csvfile) {
        CSVReader data;

        bool ret = csvCache.TryGetValue(csvfile, out data);
        if (!ret) {
            data = new CSVReader(csvfile, Load(csvfile));
            csvCache.Add(csvfile, data);
        }
        return data;
    }

    public static void Clear() {
        csvCache.Clear();
    }
    /// <summary>
    /// 读取指定的csv文件
    /// </summary>
    public static string Load(string file) {
        TextAsset data = Resources.Load(DataTablesManager.Path + file) as TextAsset;
        if (data != null) {
            string txt = data.text;
            return txt;
        }
        else {
#if UNITY_EDITOR
            debug.log(true, debug.Level.warning_2, "CSV file does not exist: " + file);
#endif
        }
        return string.Empty;
    }
}